/*
* Copyright (c) 2010 Michael Collins
*
* This file is part of TerraFirma.
*
* TerraFirma is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TerraFirma is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TerraFirma.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef TASK_THREAD_H
#define TASK_THREAD_H

#include <boost/thread/thread.hpp>
#include <queue>
#include "message_queue.h"
#include "mpi.h"
#include "message_header.h"
#include <typeinfo>
#include <cstdio>

/***
    This uses the Borland-model for template instanciation
    Perhaps we will fix it later to do it the Cfront way and
    keep a repository of template instaces, but for now, we are
    taking the easy route and perhaps duplicating code
    This being the case, the header includes definition as well
***/

namespace engine
{
    //class mpi; //forward declaration to avoid circular dependencies
    extern mpi MPI;

    const task_id get_task_id_by_name(const char* name);

    template <typename T = message_header>
    class task_thread : boost::noncopyable
    {
    protected:
        message_queue<T> msg_queue;

    public:
        task_thread(const char* classname) : tid(get_task_id_by_name(classname))
        {
            MPI.add_listener(msg_queue.ref(), tid);
        }

        virtual ~task_thread()
        {
            ;
        }

        //Returns the type name of the derived classes (in abstract case, "task_thread")
        virtual const char* name()
        {
            return "task_thread";
        }

        //The individual thread entry point. Argument is the thread id of the operating thread
        virtual void F(const boost::thread::id tid)
        {
            ;
        }

        inline void operator ()()
        {
            F(boost::this_thread::get_id());
        }

        friend class mpi; //mpi has access to the queue to push stuff on

        const task_id tid;

    };

    //Define the constructor here
    /*template <typename T>
    task_thread<T>::task_thread()
    {
        MPI.add_listener(*(reinterpret_cast<task_thread<message_header>*>(this)));
    }*/
};
#endif // TASK_THREAD_H
